<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="deps" :props="defaultProps" default-expand-all :expand-on-click-node="false">
        <template v-slot="{ data }">
          <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <el-dropdown @command="depHandle($event,data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作
                  <i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <addDeps
      ref="addDeps"
      :show-dialog.sync="showDialog"
      :ori-deps="oriDeps"
      :current-id="currentId"
      @updateDeps="getDepartmentList"
    />
  </div>
</template>
<script>
import { getDepartmentList, delDept } from '@/api/department'
import { transeListToTree } from '@/utils'
import addDeps from '@/views/department/components/addDeps.vue'
export default {
  name: 'Department',
  components: {
    addDeps
  },
  data() {
    return {
      deps: [],
      oriDeps: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false,
      currentId: ''
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    depHandle(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.currentId = id
      } else if (type === 'edit') {
        this.showDialog = true
        this.currentId = id
        // prop 异步更新
        this.$nextTick(() => {
          this.$refs.addDeps.getDepDetail()
        })
      } else {
        this.$confirm('确定要删除该部门吗？').then(async() => {
          await delDept(id)
          this.$message.success('删除成功')
          this.getDepartmentList()
        })
      }
    },
    async getDepartmentList() {
      const res = await getDepartmentList()
      this.deps = transeListToTree(res, 0) // 转换成树形数据
      this.oriDeps = res // 原始数据用来后续遍历
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
